package com.ww.springboot.boot.algorithm.leetcode1;

/**
 * todo
 *
 * @author wanwei
 * @since 2022-03-15 18:27
 */
public class AQ74搜索二维矩阵 {

    public static void main(String[] args) {
        int[][] matrix = {{1}};
        System.out.println(searchMatrix(matrix, 1));
    }


    /**
     * 搜索使用二分查找即可 只用将二维数组当做一个升序的数组即可
     *
     * @param matrix
     * @param target
     * @return
     */
    public static boolean searchMatrix(int[][] matrix, int target) {
        int y = matrix.length;
        int x = matrix[0].length;
        int start = 0;
        int end = x * y - 1;
        if(start == end){
            return matrix[0][0] == target;
        }

        while (end > start) {
            int startVal = matrix[start / x][start % x];
            int endVal = matrix[end / x][end % x];
            //判断首尾是否相等
            if (startVal > target || endVal < target) {
                return false;
            }
            if (startVal == target || endVal == target) {
                return true;
            }
            if(end - start == 1){
                return false;
            }

            int middle = (end + start) / 2;
            //取中间值
            int i = middle / x;
            int j = middle % x;
            if (matrix[i][j] == target) {
                return true;
            } else if (matrix[i][j] > target) {
                end = middle;
            } else {
                start = middle;
            }
        }
        return false;
    }
}
